<template>
  <div id="root" class="app-wrapper">
    <div class="login-container">
      <div class="login-card">
        <h2 class="login-title">欢迎登录</h2>

        <vxe-form ref="loginFormRef" :data="loginForm" :rules="loginRules" @submit="handleLogin">
          <vxe-form-item title="用户名" field="username" :item-render="{}">
            <template #default>
              <vxe-input style="width: 290px;" v-model="loginForm.username" placeholder="请输入用户名" clearable></vxe-input>
            </template>
          </vxe-form-item>

          <vxe-form-item title="密码" field="password" :item-render="{}">
            <template #default>
              <vxe-password-input style="width: 290px;" v-model="loginForm.password" type="password" placeholder="请输入密码"
                clearable></vxe-password-input>
            </template>
          </vxe-form-item>

          <vxe-form-item title="验证码" field="captcha" :item-render="{}">
            <template #default>
              <div class="captcha-container">
                <vxe-input style="width: 180px;" v-model="loginForm.captcha" placeholder="请输入验证码" clearable></vxe-input>
                <div class="captcha-image" @click="refreshCaptcha">
                  <img :src="captchaImage" alt="验证码" />
                </div>
              </div>
            </template>
          </vxe-form-item>

          <vxe-form-item>
            <template #default>
              <vxe-button style="width: 290px;" type="submit" status="primary" content="登录"
                :loading="loading"></vxe-button>
            </template>
          </vxe-form-item>
        </vxe-form>

        <div class="login-footer">
          <vxe-checkbox v-model="rememberMe">记住我</vxe-checkbox>
          <vxe-button mode="text">忘记密码?</vxe-button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
 const logout = new URLSearchParams(window.location.search).get("logout");
 if (logout === "true") {
   localStorage.removeItem('token');
   localStorage.removeItem('userId');
   localStorage.removeItem('username'); 
 }

import { ref, reactive } from "vue";
import { VxeUI } from "vxe-table";
import { useRouter } from 'vue-router'

const router = useRouter();
const loginFormRef = ref(null);
const loading = ref(false);
const rememberMe = ref(false);
const captchaImage = ref("/api/captcha"); // 模拟验证码图片

const loginForm = reactive({
  username: "",
  password: "",
  captcha: "",
});

const loginRules = reactive({
  username: [
    { required: true, message: "请输入用户名" },
    { min: 4, max: 16, message: "长度在4到16个字符" },
  ],
  password: [
    { required: true, message: "请输入密码" },
    { min: 6, max: 20, message: "长度在6到20个字符" },
  ],
  captcha: [
    { required: true, message: "请输入验证码" },
    { min: 4, max: 4, message: "验证码为4位字符" },
  ],
});

const refreshCaptcha = () => {
  // 实际项目中这里应该请求后端获取新的验证码
  captchaImage.value = `/api/captcha?random=${Math.random()}`;
};

const handleLogin = async () => {
  const $form = loginFormRef.value;
  if ($form) {
    const errMap = await $form.validate();
    if (!errMap) {
      loading.value = true;
      // 模拟登录请求
      // setTimeout(() => {
      //   loading.value = false;
      //   VxeUI.modal.message({ content: '登录成功', status: 'success' });
      //   // 实际项目中这里应该跳转到首页
      // }, 1500);
      Meteor.call(
        "userLogin",
        {
          username: loginForm.username,
          password: loginForm.password,
          captcha: loginForm.captcha,
        },
        (err, res) => {
          if (err) {
            console.error("调用错误:", err.message);
          } else {
            console.log("调用成功:", res);
            if (res.status === 0) {
              // 存储 token 和用户信息
              localStorage.setItem('token', res.data.token);
              // 跳转后台首页
              router.push('/admin/index')
            }
            else {
              refreshCaptcha();
              VxeUI.modal.message({ content: res.reason, status: 'error' });
            }
            loading.value = false;
          }
        }
      );
    }

  }
};
</script>

<style scoped>
.app-wrapper {
  height: 100vh;
  width: 100vw;
  background: linear-gradient(135deg, #607d8b 0%, #90a4ae 100%);
  display: flex;
  justify-content: center;
  align-items: center;
}

.login-container {
  width: 100%;
  max-width: 420px;
  padding: 0 10px;
}

.login-card {
  background-color: #fff;
  border-radius: 10px;
  padding: 40px;
  box-shadow: 0 15px 35px rgba(0, 0, 0, 0.1);
}

.login-title {
  text-align: center;
  color: #333;
  margin-bottom: 30px;
  font-size: 24px;
  font-weight: 500;
}

.captcha-container {
  display: flex;
  align-items: center;
  gap: 10px;
}

.captcha-image {
  cursor: pointer;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  overflow: hidden;
}

.captcha-image img {
  height: 33px;
  display: block;
}

.login-footer {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 15px;
  color: #999;
}

/* 自定义 VxeTable 表单样式 */
:deep(.vxe-form--item-title) {
  display: none !important;
}

:deep(.vxe-form--item) {
  margin-bottom: 20px !important;
}

:deep(.vxe-button.type--submit) {
  width: 100%;
  height: 40px;
  margin-top: 10px;
}
</style>
